#!/usr/bin/env python
import os
import sys
import random
import string
import time

import urllib.request

debug = 0
class HTTPClient:
    def __init__(self, url, host, user_agent = None):
        self.url = url
        self.host = host
        if user_agent is None:
            self.user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36'
        else:
            self.user_agent = user_agent

        return

    def start_proxy(self, proxy = None):
        if proxy is None:
            proxy_handler = urllib2.ProxyHandler({})
        else:
            proxy_handler = urllib2.ProxyHandler({"http" : proxy})

        opener = urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener)

        return

    def start_test(self):
        headers = { 'User-Agent' : self.user_agent, "Host" : self.host }
        req = urllib.request.Request(self.url, headers = headers)
        with urllib.request.urlopen(req) as response:
            print(response.read())

        return

def Usage():
    print("python ./name <ip> <port> <hostname> <type>")
    print("type 0: urltest; type 1:argtest")

tmp_urlfile = "./test_urls"
tmp_argfile = "./email_full.txt"

def create_random_arg():
    full_url = "/testarg.html"

    argname = "testacount"
    argvalue_len = random.randint(3, 16)
    argvalue = ''.join(random.sample(string.ascii_letters + string.digits, argvalue_len))
    full_url = '?%s%s=%s' % (full_url, argname, argvalue)

    return full_url



def create_random_url():
    full_url = "/"
    maxcnt = random.randint(1, 9)
    x = 0
    while x < maxcnt:
        path_len = random.randint(3, 12)
        url = ''.join(random.sample(string.ascii_letters + string.digits, path_len))
        full_url = '%s%s%s' % (full_url, url, "/")
        x += 1

    maxcnt = random.randint(0, 2)
    x = 0
    while x < maxcnt:
        argname_len = random.randint(3, 9)
        argvalue_len = random.randint(3, 16)
        if  x == 0:
            full_url = '%s%s' % (full_url, "?")
        else:
            full_url = '%s%s' % (full_url, "&")

        argname = ''.join(random.sample(string.ascii_letters + string.digits, argname_len))
        argvalue = ''.join(random.sample(string.ascii_letters + string.digits, argvalue_len))
        full_url = '%s%s=%s' % (full_url, argname, argvalue)
        x += 1

    return full_url

def create_argfile(filename):
    #max_urlcnt = 40960
    max_urlcnt = 1
    i = 0
    if os.path.exists(filename):
        os.remove(filename)
    
    with open(filename, 'w') as f:
        while i < max_urlcnt:
            url = create_random_url()
            f.write(url)
            f.write('\n')
            i += 1



def create_urlfile(filename):
    max_urlcnt = 40960
    i = 0
    if os.path.exists(filename):
        os.remove(filename)
    
    with open(filename, 'w') as f:
        while i < max_urlcnt:
            url = create_random_url()
            f.write(url)
            f.write('\n')
            i += 1

def test_http_request(server_ip, server_port):
    cli_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    cli_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    cli_socket.connect()

def test_client(filename, server_ip, server_port, server_host):
    i = 0
    with open(filename, 'r') as f:
        while True:
            line = f.readline()
            if not line: break
            url = 'http://%s:%d%s' % (server_ip, server_port, line) 
            print("test url :%s" % (url))
            
            client = HTTPClient(url, server_host)
            client.start_test()

            i += 1
            if debug == 1:
                time.sleep(2)
                url = 'http://%s:%d%s' % (server_ip, server_port, line) 
                print("test url :%s" % (url))
            
                client = HTTPClient(url, server_host)
                client.start_test()

                break
    print("total url count:%d" % (i))

def test_client_arg(filename, server_ip, server_port, server_host):
    i = 0
    with open(filename, 'r') as f:
        while True:
            line = f.readline()
            if not line: break
            url = 'http://%s:%d/login.html?acountname=%s' % (server_ip, server_port, line) 
            print("test url :%s" % (url))
            
            client = HTTPClient(url, server_host)
            client.start_test()

            i += 1
            if debug == 1:
                time.sleep(2)
                url = 'http://%s:%d%s' % (server_ip, server_port, line) 
                print("test url :%s" % (url))
            
                client = HTTPClient(url, server_host)
                client.start_test()

                break
            #break
    print("total url count:%d" % (i))



if __name__ == "__main__":
    if len(sys.argv) != 5:
        Usage()
        exit()

    server_ip = sys.argv[1]
    server_port = int(sys.argv[2])
    server_host = sys.argv[3]
    test_type = int(sys.argv[4])
    print("test server %s:%d, host:%s url file:%s" % \
        (server_ip, server_port, server_host, tmp_urlfile))
    
    if test_type == 0:
        create_urlfile(tmp_urlfile)
        test_client("urls", server_ip, server_port, server_host)
    elif test_type == 1:
        test_client_arg(tmp_argfile, server_ip, server_port, server_host)


